package com.ficus.road.maintain.file;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Optional;

/**
 * @author xiawen yang
 * @date 2022/6/21 上午11:08
 */
@Service
public class FileServiceImpl implements FileService {

    @Value("${fileClientConfig}")
    private String fileClientConfig;

    @Getter
    private FileClient fileClient;

    @Autowired
    private FileClientFactory fileClientFactory;

    @Autowired
    private List<FileClientConfig> fileClientConfigList;

    @PostConstruct
    void init() {
        Optional<FileClientConfig> optional = fileClientConfigList.stream().filter(item -> item.getConfigName().equals(fileClientConfig)).findFirst();
        if (optional.isEmpty()) {
            throw new RuntimeException("存储配置有误！");
        }

        fileClientFactory.createFileClient(fileClientConfig, optional.get());
        fileClient = fileClientFactory.getFileClient(fileClientConfig);
    }

    @Override
    public UploadResult upload(byte[] content, String path) throws Exception {
        return fileClient.upload(content, path);
    }

    @Override
    public void uploadDirect(byte[] content, String path) {
        fileClient.uploadDirect(content, path);
    }

    @Override
    public Object getContent(String path) {
        return fileClient.getContent(path);
    }

    @Override
    public Object getContentByUrl(String url) {
        return fileClient.getContentByUrl(url);
    }
}
